package com.bosicloud.cmb.ibp.account.service.impl;


import com.bosicloud.cmb.ibp.QueueNames;
import com.bosicloud.cmb.ibp.account.common.model.IbpUser;
import com.bosicloud.cmb.ibp.account.common.model.IbpUserApiKey;
import com.bosicloud.cmb.ibp.account.dao.IbpUserApiKeyMapper;
import com.bosicloud.cmb.ibp.account.dao.IbpUserMapper;
import com.bosicloud.cmb.ibp.account.service.AccountManagerService;
import com.bosicloud.cmb.ibp.aws.adapter.commom.vo.CreateApiKeyVO;
import com.bosicloud.cmb.ibp.commom.dto.exchange.ExchangeMessage;
import com.bosicloud.cmb.ibp.commom.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

import static com.bosicloud.cmb.ibp.account.common.constant.EnvConstants.LIST_ENV;
import static com.bosicloud.cmb.ibp.account.common.constant.EnvConstants.TEST_ENV;
import static com.bosicloud.cmb.ibp.commom.dto.exchange.ExchangeAction.CREATE_KEY;

@Slf4j
@Service
public class AccountManagerServiceImpl implements AccountManagerService {

    private final IbpUserMapper ibpUserMapper;

    private final IbpUserApiKeyMapper ibpUserApiKeyMapper;

    private final QueueMessagingTemplate messagingTemplate;

    private final QueueNames queueNames;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public AccountManagerServiceImpl(IbpUserMapper ibpUserMapper,
                                     IbpUserApiKeyMapper ibpUserApiKeyMapper,
                                     QueueNames queueNames,
                                     QueueMessagingTemplate messagingTemplate) {
        this.ibpUserMapper = ibpUserMapper;
        this.ibpUserApiKeyMapper = ibpUserApiKeyMapper;
        this.queueNames = queueNames;
        this.messagingTemplate = messagingTemplate;
    }

    @Override
    public IbpUser login(String username, String password) {
        IbpUser ibpUser = ibpUserMapper.login(username, password);
        if (Objects.nonNull(ibpUser)) {
            ibpUser.setPassword("*******");
            sendCreateApiKeyMessage(ibpUser.getId());
        }
        return ibpUser;
    }

    private void sendCreateApiKeyMessage(Integer userId) {

        if (CollectionUtils.isEmpty(searchUserApiKeyListByUserId(userId))) {

            try {
                LIST_ENV.forEach(env -> this.sendMessage(queueNames.getRequest(),
                        CREATE_KEY, new CreateApiKeyVO(userId, TEST_ENV.equalsIgnoreCase(env))));
            } catch (MessagingException e) {
                log.error("send create api key message error:{}", e.getMessage(), e);
            }
        } else {
            log.info("current user have api key.");
        }
    }

    @Override
    public Integer createUserApiKey(IbpUserApiKey ibpUserApiKey) {
        return ibpUserApiKeyMapper.createUserApiKey(ibpUserApiKey);
    }

    @Override
    public List<IbpUserApiKey> searchUserApiKeyListByUserId(Integer userId) {
        return ibpUserApiKeyMapper.searchUserApiKeyListByUserId(userId);
    }

    private void sendMessage(String targetQueueName, String action, Object data) {

        log.info("### Send message to target queue name is:{},DATA is:{}",
                targetQueueName, JsonUtil.toJson(data));
        messagingTemplate.convertAndSend(targetQueueName,
                ExchangeMessage.builder()
                        .Action(action)
                        .data(data)
                        .build());
        log.info("### Send message end.");
    }
}
